package com.fowo.api.service.handleWork;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.constants.RequestMethodKind;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.service.impl.implCore.LingxingServiceImpl;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.RestUtilLingXing;
import com.fowo.api.entity.Supplier;
import com.fowo.api.entity.Warehouse;
import com.fowo.api.model.stock.in.StockInPushLingXingAction;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Component
public class StockInPushLingXing implements StockInPushLingXingAction {
    @Resource
    private StockInServiceImpl stockInService;
    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private LingxingServiceImpl lingxingService;
    @Resource
    private Common common;
    @Resource
    private RestUtilLingXing restUtilLingXing;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private SupplierServiceImpl supplierService;
    @Resource
    private ProductServiceImpl productService;
    @Resource
    private ProductPriceServiceImpl productPriceService;

    private static final String STORAGE_ORDER_ADD = "https://openapi.lingxing.com" +
            "/erp/sc/routing/storage/storage/orderAdd";

    @Override
    public void run(Long id) throws Exception {
        StockInVo stockInVo = stockInService.getVoById(id);
        if (stockInVo == null) {
            throw new Exception("入库单不存在");
        }
        Map<String, Object> requestBody = buildData(stockInVo);
        Object res = push(requestBody);
        JSONObject result = JSONUtil.parseObj(res);
        if (result.getInt("code") != 0) {
            Assert.isTrue(false, "推送入库单失败，原因："+ result.getStr("error_details"));
        }
        stockInVo.setIsPush(true);
        stockInService.updateById(stockInVo);
    }

    /**
     * 推送领星
     * @param requestBody
     */
    public Object push(Map<String, Object> requestBody){
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode, "Lingxing"), false);
        final DataContextModel.DatainterfaceAuthorityModel invoke = BeanUtil.copyProperties(entityAuthority, new DataContextModel().new DatainterfaceAuthorityModel().getClass());
        String accessToken = StrUtil.toStringOrNull(lingxingService.getAuth(invoke));
        String appId = common.getAuthoritySimpleFactory(invoke, "appId");
        com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
        params.put("access_token", accessToken);
        params.put("app_key", appId);
        params.put("timestamp", System.currentTimeMillis() / 1000);
        Object res;
        try {
            res = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(), params, STORAGE_ORDER_ADD, null, requestBody);
        } catch (Exception ex) {
            throw new RuntimeException(StrUtil.format("推送领星入库单发生异常 "));
        }
        return res;
    }

    /**
     * 构建数据
     * @param stockInVo
     * @return
     */
    public Map<String, Object> buildData(StockInVo stockInVo) throws Exception {
        Map<String, Object> requestBody = new HashMap<>();
        final Warehouse warehouse = warehouseService.getById(stockInVo.getWarehouse());
        requestBody.put("sys_wid",warehouse.getWid());
        int type = 0;
        switch (stockInVo.getReceiptType()){
            case "RK002":
                type = 2;
                break;
            case "RK003":
                type = 26;
                break;
            case "RK004":
                type = 27;
                break;
            default:
                break;
        }
        requestBody.put("type",type);
        final Supplier supplier = supplierService.getById(stockInVo.getSupplier());
        requestBody.put("sys_supplier_id",supplier.getSupplierCode());
//        requestBody.put("supplier_id",stockInVo.getSupplier().toString());
        if(StringUtils.isNotBlank(stockInVo.getRemarks()) ){
            requestBody.put("remark",stockInVo.getRemarks());
        }
        if(stockInVo.getFreight() != null){
            requestBody.put("ship_fee",stockInVo.getFreight());
        }
        if(stockInVo.getOtherExpenses() != null){
            requestBody.put("other_fee",stockInVo.getOtherExpenses());
        }
        int feePartType = 0;
        switch (stockInVo.getCostAllocationType()){
            case "1":
                feePartType = 0;
                break;
            case "2":
                feePartType = 1;
                break;
            case "3":
                feePartType = 2;
                break;
            default:
                break;
        }
        requestBody.put("fee_part_type",feePartType);
        if(stockInVo.getPurchaseOrderCode()==null){
            throw new RuntimeException("订单编号不能为空!");
        }
        requestBody.put("order_sn",stockInVo.getPurchaseOrderCode());
        requestBody.put("inbound_time", DateUtil.formatDate(stockInVo.getWarehousingDate()));
        JSONArray array = new JSONArray();
        for(StockInProductItemVo stockInProduct : stockInVo.getProductList()){

//            Long productId = stockInProduct.getProductId();
//            Product product = productService.getById(productId);
//            if (product == null) {
//                throw new Exception("产品不存在");
//            }
//            BigDecimal price = product.getProcurementCost();
//            if(price == null){
//                throw new Exception("价格不能为空");
//            }
            if(stockInProduct.getGoodProduct() == null&&stockInProduct.getDefectiveProduct() == null){
                throw new Exception("数量不能为空");
            }
            if(stockInProduct.getLxPrice() == null){
                throw new Exception("领星价格不能为空");
            }
            JSONObject object = new JSONObject();
            object.putOpt("sku",stockInProduct.getSku());
            object.putOpt("good_num",stockInProduct.getGoodProduct() == null ? 0 : stockInProduct.getGoodProduct());
            object.putOpt("bad_num",stockInProduct.getDefectiveProduct() == null ? 0 : stockInProduct.getDefectiveProduct());
            object.putOpt("price",stockInProduct.getLxPrice().setScale(2, RoundingMode.HALF_UP).toString());
            object.putOpt("seller_id",stockInProduct.getShopId() == null ? 0 : shopInfoService.getById(stockInProduct.getShopId()).getShopCode());
            object.putOpt("fnsku",stockInProduct.getLxFnsku() == null ? "" : stockInProduct.getLxFnsku());
            array.add(object);
        }
        requestBody.put("product_list",array);
        return  requestBody;
    }
}
